import LanguageType, {default as LanguageType} from "./LanguageType";

export default class LanguageMngTs {

    private static languageObjs : Object = {}
    private static language : number = LanguageType.ENGLISH

    constructor(){

    }

    private static _instance:LanguageMngTs = null;

    public static getInstance():LanguageMngTs{
        if(this._instance == null){
            this._instance = new LanguageMngTs();
        }
        return this._instance;
    }

    public static loadLanguage(language : number,cb?){
        if(!language) language = LanguageType.ENGLISH
        this.language = language
        let obj = this.languageObjs[language]
        if(obj){
            if(cb) cb()
            return
        }

        let path = "languages/"
        if(language === LanguageType.ENGLISH){
            path += "english"
        }else if(language === LanguageType.HINDI){
            path += "hindi"
        }else if(language === LanguageType.TAIMIL){
            path += "taimil"
        }else if(language === LanguageType.TALUGU){
            path += "talugu"
        }else if(language === LanguageType.GULILATTER){
            path += "gugilatter"
        }else if(language === LanguageType.MALATY){
            path += "malaty"
        }else {
            path += "english"
        }

        cc.loader.loadRes(path,cc.TextAsset,function (err, assets) {
            if(err){
                cc.error(err)
                return
            }

            let text = assets.text
            this.languageObjs[language] = text.split(new RegExp('\\r\\n|\\r|\\n'));
            if(cb) cb()
        }.bind(this))
    }

    /**
     * 可以只传入一个index作为参数
     * @param language
     * @param index
     * @param cb
     * @returns {*}
     */
    public static getSentence(language,index?,cb?){
        if(arguments.length === 1) {
            let obj = this.languageObjs[this.language]
            if (!obj){
                return "notload"
            }
            else return obj[arguments[0]]
        }

        let obj = this.languageObjs[language]
        if(!obj) {
            this.loadLanguage(language,function () {
                if(cb) cb(this.languageObjs[this.language][index])
            }.bind(this))
        }else {
            if(cb) cb(obj[index])
        }
    }
};